package com.example.controller;

import com.example.dao.PriceMapper;
import com.example.entity.Price;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/price")

public class PriceController {
    @Autowired
    private PriceMapper priceMapper;

    @GetMapping(value = "getPriceAll/{page}", produces = "text/html;charset=UTF-8")
    public String getPriceAll(@PathVariable int page) throws Exception {
        Map<String, Object> data = new HashedMap();
        data.put("currIndex", (page - 1) * 15);
        data.put("pageSize", 15);
        List<Price> pList = priceMapper.selectAll(data);

        pList.stream().forEach(p->{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = simpleDateFormat.format(p.getDatachangeLasttime());
            p.setDateDesc(dateString);
        });

        ObjectMapper mapper = new ObjectMapper();
        String JSONString = mapper.writeValueAsString(pList);
        return JSONString;
    }

    @GetMapping(value = "getSuffix/{id}")
    public String getsuffix(@PathVariable int id) throws Exception {
        Price p = priceMapper.selectByPrimaryKey(id);
        String suffix = p.getFile().substring(p.getFile().lastIndexOf(".") + 1);
        if("jpg".equals(suffix) || "png".equals(suffix) || "bmp".equals(suffix)){
            suffix = "picture";
        }
        ObjectMapper mapper = new ObjectMapper();
        String JSONString = mapper.writeValueAsString(suffix);
        return JSONString;
    }

    @GetMapping(value = "getpic/{id}")
    public void getOne(@PathVariable int id, HttpServletResponse response) throws Exception {
        Price p = priceMapper.selectByPrimaryKey(id);
        String URL = "/C:/ftp/"+p.getFile();
        File imgFile = new File(URL);
        FileInputStream fin= null;
        OutputStream output=null;
        try {
            output = response.getOutputStream();
            fin = new FileInputStream(imgFile);
            byte[] arr = new byte[1024*10];
            int n;
            while((n=fin.read(arr))!= -1){
                output.write(arr, 0, n);
            }
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping(value = "getfile/{id}")
    public String getfile(@PathVariable int id,HttpServletResponse response) throws IOException{
        Price p = priceMapper.selectByPrimaryKey(id);
        String URL = "/C:/ftp/"+p.getFile();
        File file = new File(URL);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(p.getFile(),"utf-8"));// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "下载失败";
    }

    @GetMapping(value = "getcount",produces = "text/html;charset=UTF-8")
    public String getPriceCounts() throws Exception{
        int count = priceMapper.count();
        ObjectMapper mapper = new ObjectMapper();
        String JSONString =  mapper.writeValueAsString(count);
        return JSONString;
    }

    @RequiresPermissions("super")
    @RequestMapping(value = "add",produces = "text/html;charset=UTF-8")
    public String addPrice(@RequestBody Price p) throws IOException {
        p.setDatachangeLasttime(new Date());
        int result = priceMapper.insert(p);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(result);
    }

    @RequiresPermissions("super")
    @RequestMapping(value = "update",produces = "text/html;charset=UTF-8")
    public String updatePrice(@RequestBody Price p) throws IOException {
        p.setDatachangeLasttime(new Date());
        if ("".equals(p.getFile())){
            p.setFile(null);
        }
        int result = priceMapper.updateByPrimaryKey(p);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(result);
    }

    @RequiresPermissions("super")
    @RequestMapping(value = "delete/{id}",produces = "text/html;charset=UTF-8")
    public String deletePrice(@PathVariable int id)throws IOException{
        int result = priceMapper.deleteByPrimaryKey(id);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(result);
    }
}